from flask import Blueprint,jsonify,request
# from werkzeug.datastructures import D

from db import Dd
from tool import rs
import json
bp_buli_list = Blueprint('huli_list',__name__)

@bp_buli_list.route('/getlist')
def getlist():
    sql = 'select * from holiday_type'
    db = Dd()
    
    res = db.get_all(sql)
    return jsonify({'code':200,'list':res})

@bp_buli_list.route('/getresourcedata',methods=['GET','POST'])
def getresourcedata():
    #从redis取，如果有直接返回
    db = Dd()

    if request.method =='GET':

    
        values = rs.str_get('dataresouce')
        if values:
            list = eval(values)
        else:
            #如果没有查询
            sql = "select * from data_source"
            res = db.get_all(sql)
            list = []
            if res:
                for i in res:
                    dict={'id':i['id'],'name':i['name']}
                    sql1 = "select id,name,type from %s"%(i['tablename'])
                    subres = db.get_all(sql1)
                    dict['mes'] = subres
                    list.append(dict)
            #存入redis
            rs.str_set('dataresouce',json.dumps(list))
        return jsonify({"code":200,'list':list})

    else:
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update workflow set params='{}' where id = {}".format(data['mes'], int(data['id']))
        print(sql)
        db.update(sql)
        return jsonify({'code':200})

@bp_buli_list.route('/workflow')
def workflow():
    # data = request.data
    # if data:
    #     data = json.loads(data)
    # else:
    #     data = request.form
    id = request.args.get('id') 
    # print(data)
    sql = 'select * from workflow where id = %d'%(int(id))
    db = Dd()
    res = db.get_one(sql)
    return jsonify({'code':200,'workf':res})

def getdeptdata(data):
    tree = {}
    list=[]
    db1 = Dd()

    for i in data:
        tree[i['id']] = i
    for j in data:
        auid = j['auid']
        if not auid:
            j['type']=1
            list.append(j)
        else:
            if 'children' not in tree[auid]:
                tree[auid]['children']=[]
            #查询此部门下所有员工
            sql = "select * from user where dept_id={}".format(j['id'])
            res = db1.get_all(sql)
            userlist=[]
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type']=2
            tree[auid]['children'].append(j)

    return list

@bp_buli_list.route('/getcomanyuser')
def getcomanyuser():
    #获取所有公司及所有部门
    db1 = Dd()

    sql = "select * from organ"
    res = db1.get_all(sql)
    mes = getdeptdata(res)
    return jsonify({'code':200,'list':mes})
    # 数据重组，查询员工
@bp_buli_list.route('/taskm',methods=['POST'])
def taskm():
    db1 = Dd()

    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form

    title = data['title']
    params = data['params']
    auditids = data['auditids']
    #添加任务
    sql = "insert into task(title,params,next_audit,status) values('%s','%s','%s',1)"%(title,params,auditids,auditids[0])
    db1.update(sql)
 
    sql1 = "select id,title from task where title='%s'"%(title)
    task = db1.get_one(sql1)
    #把当前任务加到redis中，选用hash类型
    key='task%d'%(auditids[0])
    rs.insert_hash(key,task['id'],task['title'])
    return jsonify({"code":200})

#待我审批
@bp_buli_list.route('/mytaskaudit')
def mytaskaudit():
    
    id = request.args.get('id')
    #从redis中获取我的任务列表
    key='task%d'%(int(id))
    print(key)
    task = rs.get_all_hash(key)
    list=[]
    for k,v in task.items():
        id = str(k,encoding='utf8')
        title = str(v,encoding='utf8')
        list.append({'id':id,'title':title})

    return jsonify({"code":200,'list':list})